<template>
  <view class="detail-container">
    <!-- 头部标题 -->
    <view class="detail-header">
      <view class="header-content">
        <text class="detail-title">日成本分析详情</text>
        <text class="detail-subtitle">{{ getDateOnly(detailForm.reportDate) + '日成本分析' }}</text>
      </view>
    </view>

    <!-- 详情内容 -->
    <view class="detail-content">
      <!-- 基本信息 -->
      <view class="detail-section">
        <view class="section-header">
          <uni-icons type="chat" size="20" color="#007AFF"></uni-icons>
          <text class="section-title">基本信息</text>
        </view>
        <view class="detail-grid">
          <view class="detail-item">
            <text class="detail-label">分析日期</text>
            <text class="detail-value">{{ getDateOnly(detailForm.reportDate) || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">所属项目</text>
            <text class="detail-value">{{ getProjectNameById(detailForm.projectId) || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">填报人</text>
            <text class="detail-value">{{ detailForm.createBy || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">创建时间</text>
            <text class="detail-value">{{ changeTime(detailForm.createTime) || '-' }}</text>
          </view>
        </view>
      </view>

      <!-- 产值与利润 -->
      <view class="detail-section">
        <view class="section-header">
          <uni-icons type="medal" size="20" color="#52c41a"></uni-icons>
          <text class="section-title">产值与利润</text>
        </view>
        <view class="detail-grid">
          <view class="detail-item">
            <text class="detail-label">当日产值</text>
            <text class="detail-value amount-value">¥{{ detailForm.dailyOutput || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">当日成本</text>
            <text class="detail-value amount-value">¥{{ detailForm.dailyCost || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">当日实现利润</text>
            <text class="detail-value amount-value profit-amount">¥{{ detailForm.dailyProfit || '-'
            }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">当日利润率</text>
            <text class="detail-value profit-value">
              {{ detailForm.dailyProfitRate != null
                ? Number(detailForm.dailyProfitRate * 100).toFixed(2) + "%"
                : "--" }}
            </text>
          </view>
          <view class="detail-item">
            <text class="detail-label">累计完成产值</text>
            <text class="detail-value amount-value">¥{{ detailForm.totalOutput || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">累计成本</text>
            <text class="detail-value amount-value">¥{{ detailForm.totalCost || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">累计实现利润</text>
            <text class="detail-value amount-value profit-amount">¥{{ detailForm.totalProfit || '-'
            }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">累计实现利润率</text>
            <text class="detail-value profit-value">
              {{ detailForm.totalProfitRate != null
                ? Number(detailForm.totalProfitRate * 100).toFixed(2) + "%"
                : "--" }}
            </text>
          </view>
        </view>
      </view>

      <!-- 备注信息 -->
      <view class="detail-section" v-if="detailForm.remark">
        <view class="section-header">
          <uni-icons type="compose" size="20" color="#13c2c2"></uni-icons>
          <text class="section-title">备注信息</text>
        </view>
        <view class="detail-grid">
          <view class="detail-item full-width">
            <text class="detail-label">备注说明</text>
            <text class="detail-value text-content">{{ detailForm.remark || '-' }}</text>
          </view>
        </view>
      </view>

      <!-- 附件信息 -->
      <view class="detail-section" v-if="attachmentList.length > 0">
        <view class="section-header">
          <uni-icons type="paperclip" size="20" color="#722ed1"></uni-icons>
          <text class="section-title">附件</text>
        </view>
        <view class="detail-grid">
          <view v-for="(file, index) in attachmentList" :key="index" class="attachment-item"
            @click="handlePreview(file)">
            <view class="attachment-preview">
              <text class="preview-text">预览</text>
              <uni-icons type="forward" size="16" color="#999"></uni-icons>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提示 -->
    <view class="footer-tip">
      <text class="tip-text">更多详细信息请登录电脑端查看。</text>
    </view>
  </view>
</template>

<script>
import { listAllProjectContractInfo, getProjectProfitReport } from '@/api/production/index'
import { fileLinkTransfer, fileLinkLooking } from '@/api/production/file'

export default {
  data() {
    return {
      detailForm: {},
      projectList: [],
      projectIdToName: {},
      attachmentList: []
    }
  },
  onLoad(options) {
    if (options.id) {
      this.loadDetailData(options.id)
    }
    this.loadProjectList()
  },
  methods: {
    // 平台判断
    isIOS() {
      try {
        const info = uni.getSystemInfoSync && uni.getSystemInfoSync()
        if (info && info.osName) {
          return String(info.osName).toLowerCase() === 'ios'
        }
        if (info && info.platform) {
          return String(info.platform).toLowerCase() === 'ios'
        }
      } catch (e) { }
      if (typeof navigator !== 'undefined') {
        const ua = navigator.userAgent || ''
        return /iPad|iPhone|iPod/i.test(ua)
      }
      return false
    },
    // 构造 Office 在线预览链接
    buildOfficeViewerUrl(src) {
      if (!src) return ''
      return `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(src)}`
    },
    // 提取文件扩展名（用于 openDocument 在 iOS 指定精确类型）
    getFileExtension(nameOrUrl) {
      if (!nameOrUrl) return ''
      let clean = nameOrUrl
      try {
        if (nameOrUrl.includes('://') || nameOrUrl.startsWith('http')) {
          const u = new URL(nameOrUrl)
          clean = u.pathname
        }
      } catch (e) { }
      clean = clean.split('?')[0].split('#')[0]
      const parts = clean.split('.')
      if (parts.length < 2) return ''
      return parts.pop().toLowerCase()
    },
    // 加载详情数据
    async loadDetailData(id) {
      try {
        uni.showLoading({
          title: '加载中...'
        })
        const response = await getProjectProfitReport(id)
        this.detailForm = response.data || response
        // 处理附件列表
        this.processAttachmentList()
        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
        console.error('获取详情失败:', error)
        uni.showToast({
          title: '获取详情失败',
          icon: 'none'
        })
      }
    },

    // 处理附件列表
    processAttachmentList() {
      console.log(this.detailForm)
      this.attachmentList = []
      const attachmentField = this.detailForm.downloadurl

      if (!attachmentField) return

      // 如果是字符串，转换为数组
      if (typeof attachmentField === 'string') {
        if (attachmentField.trim()) {
          this.attachmentList.push({
            url: attachmentField
          })
        }
      }
      // 如果是数组
      else if (Array.isArray(attachmentField)) {
        attachmentField.forEach(item => {
          if (typeof item === 'string' && item.trim()) {
            this.attachmentList.push({
              url: item
            })
          } else if (item && typeof item === 'object' && item.url) {
            this.attachmentList.push({
              url: item.url
            })
          }
        })
      }

      // 只保留文档类型的附件
      this.attachmentList = this.attachmentList.filter(file => {
        const fileType = this.getFileIconType(file.url)
        return ['pdf', 'word', 'excel', 'ppt'].includes(fileType)
      })
    },

    // 加载项目列表
    async loadProjectList() {
      try {
        const response = await listAllProjectContractInfo()
        const list = response.data || response.rows || []
        this.projectList = list
        // 构建项目ID到名称的映射
        this.projectIdToName = {}
        list.forEach(item => {
          const projectId = item.id || item.projectId
          const projectName = item.projectName || item.name
          if (projectId) {
            this.projectIdToName[projectId] = projectName
          }
        })
      } catch (error) {
        console.error('获取项目列表失败:', error)
      }
    },

    // 根据项目ID获取项目名称
    getProjectNameById(projectId) {
      if (projectId == null || projectId === '') return ''
      return this.projectIdToName[projectId] || projectId
    },

    // 只保留年月日
    getDateOnly(datetime) {
      if (!datetime) return ''
      const str = typeof datetime === 'string' ? datetime : this.changeTime(datetime)
      const match = str.match(/^\d{4}-\d{2}-\d{2}/)
      return match ? match[0] : str
    },

    // 时间格式化
    changeTime(time) {
      if (!time) return ''
      const date = new Date(time)
      if (isNaN(date.getTime())) return time
      const pad = n => n < 10 ? '0' + n : n
      const y = date.getFullYear()
      const m = pad(date.getMonth() + 1)
      const d = pad(date.getDate())
      const h = pad(date.getHours())
      const min = pad(date.getMinutes())
      const s = pad(date.getSeconds())
      return `${y}-${m}-${d} ${h}:${min}:${s}`
    },

    // 获取文件图标类型
    getFileIconType(fileName) {
      if (!fileName) return 'file'
      // 处理 URL，移除查询参数和锚点
      let cleanName = fileName
      try {
        // 如果是完整的 URL，尝试解析
        if (fileName.includes('://') || fileName.startsWith('http')) {
          const urlObj = new URL(fileName)
          cleanName = urlObj.pathname
        } else {
          // 移除查询参数和锚点
          cleanName = fileName.split('?')[0].split('#')[0]
        }
      } catch (e) {
        // 如果不是标准 URL，移除查询参数和锚点
        cleanName = fileName.split('?')[0].split('#')[0]
      }
      const ext = cleanName.split('.').pop().toLowerCase()
      if (['doc', 'docx'].includes(ext)) return 'word'
      if (['xls', 'xlsx'].includes(ext)) return 'excel'
      if (['ppt', 'pptx'].includes(ext)) return 'ppt'
      if (['pdf'].includes(ext)) return 'pdf'
      if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'svg', 'webp'].includes(ext)) return 'image'
      if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'mpeg', 'mpg'].includes(ext)) return 'video'
      if (['txt'].includes(ext)) return 'txt'
      if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'zip'
      return 'file'
    },

    // 预览文件（与 macos-file-manager 保持一致）
    async handlePreview(file) {
      if (!file.url) {
        uni.showToast({
          title: '无效的预览链接',
          icon: 'none'
        })
        return
      }

      try {
        let newUrl = ''
        const type = this.getFileIconType(file.url)

        if (['pdf', 'word', 'excel', 'ppt'].includes(type)) {
          // #ifdef MP-WEIXIN
          const transferRes = await fileLinkTransfer(file.url)
          newUrl = transferRes.data.url
          // #endif
          // #ifndef MP-WEIXIN
          // 小程序和苹果手机要求使用直链下载再预览：iOS 或 Office 文档统一先拿直链
          if (this.isIOS() || type === 'word' || type === 'excel' || type === 'ppt') {
            const transferResH5 = await fileLinkTransfer(file.url)
            newUrl = transferResH5.data.url
          } else {
            const lookRes = await fileLinkLooking(file.url)
            newUrl = lookRes.data.url
          }
          // #endif
        } else {
          newUrl = file.url
        }

        if (!newUrl) {
          uni.showToast({
            title: '获取预览链接失败',
            icon: 'none'
          })
          return
        }

        if (['pdf', 'word', 'excel', 'ppt'].includes(type)) {
          // #ifdef MP-WEIXIN
          try {
            uni.showLoading({ title: '打开中...', mask: true })
            uni.downloadFile({
              url: newUrl,
              success: (res) => {
                if (res.statusCode === 200) {
                  uni.openDocument({
                    filePath: res.tempFilePath,
                    showMenu: true,
                    fileType: type === 'word' ? 'doc' : (type === 'excel' ? 'xls' : (type === 'ppt' ? 'ppt' : 'pdf')),
                    success: () => { },
                    fail: () => {
                      uni.showToast({ title: '打开失败', icon: 'none' })
                    },
                    complete: () => { uni.hideLoading() }
                  })
                } else {
                  uni.hideLoading()
                  uni.showToast({ title: '下载失败', icon: 'none' })
                }
              },
              fail: () => {
                uni.hideLoading()
                uni.showToast({ title: '下载失败', icon: 'none' })
              }
            })
          } catch (e) {
            uni.hideLoading()
            uni.showToast({ title: '打开失败', icon: 'none' })
          }
          // #endif
          // #ifndef MP-WEIXIN
          if (this.isIOS()) {
            // iOS：APP 端下载 + openDocument；H5 端直接打开直链
            // #ifdef APP-PLUS
            try {
              uni.showLoading({ title: '打开中...', mask: true })
              uni.downloadFile({
                url: newUrl,
                success: (res) => {
                  if (res.statusCode === 200) {
                    const ext = this.getFileExtension(file.url)
                    const supported = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']
                    const fileType = supported.includes(ext) ? ext : 'pdf'
                    uni.openDocument({
                      filePath: res.tempFilePath,
                      showMenu: true,
                      fileType,
                      success: () => { },
                      fail: () => { uni.showToast({ title: '打开失败', icon: 'none' }) },
                      complete: () => { uni.hideLoading() }
                    })
                  } else {
                    uni.hideLoading()
                    uni.showToast({ title: '下载失败', icon: 'none' })
                  }
                },
                fail: () => {
                  uni.hideLoading()
                  uni.showToast({ title: '下载失败', icon: 'none' })
                }
              })
            } catch (e) {
              uni.hideLoading()
              uni.showToast({ title: '打开失败', icon: 'none' })
            }
            // #endif
            // #ifdef H5
            uni.navigateTo({
              url: `/pages/common/webview/index?url=${encodeURIComponent(newUrl)}&title=${encodeURIComponent('文件预览')}`
            })
            // #endif
          } else {
            // 非 iOS H5：Office 用微软预览；PDF 直接打开
            const finalUrl = (type === 'word' || type === 'excel' || type === 'ppt')
              ? this.buildOfficeViewerUrl(newUrl)
              : newUrl
            uni.navigateTo({
              url: `/pages/common/webview/index?url=${encodeURIComponent(finalUrl)}&title=${encodeURIComponent('文件预览')}`
            })
          }
          // #endif
        } else {
          uni.navigateTo({
            url: `/pages/common/webview/index?url=${encodeURIComponent(newUrl)}&title=${encodeURIComponent('文件预览')}`
          })
        }
      } catch (error) {
        console.error('预览失败:', error)
        uni.showToast({
          title: '预览失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.detail-header {
  background: linear-gradient(135deg, #007AFF 0%, #5AC8FA 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  position: relative;
}

.header-content {
  text-align: center;
}

.detail-title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.detail-subtitle {
  display: block;
  font-size: 28rpx;
  opacity: 0.9;
}

.detail-content {
  padding: 30rpx;
}

.detail-section {
  background: white;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background: #f8f9fa;
  border-bottom: 1rpx solid #eee;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-left: 15rpx;
}

.detail-grid {
  padding: 30rpx;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.detail-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.detail-item.full-width {
  flex-direction: column;
  width: 100%;
}

.detail-item.full-width .detail-value {
  width: 100%;
}

.detail-label {
  font-size: 28rpx;
  color: #666;
  min-width: 200rpx;
  margin-right: 20rpx;
  line-height: 1.5;
}

.detail-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  word-break: break-all;
}

.text-content {
  background: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-top: 15rpx;
  white-space: pre-wrap;
  width: 100%;
  box-sizing: border-box;
}

/* 金额样式 */
.amount-value {
  font-weight: 600;
  color: #333;
}

.total-cost {
  font-size: 32rpx;
  color: #ff4d4f;
  font-weight: bold;
}

.profit-amount {
  color: #52c41a;
  font-weight: bold;
}

.profit-value {
  font-size: 30rpx;
  font-weight: bold;
  color: #1890ff;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .detail-content {
    padding: 20rpx;
  }

  .detail-grid {
    padding: 20rpx;
  }

  .detail-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .detail-label {
    min-width: auto;
    margin-right: 0;
    margin-bottom: 10rpx;
  }
}

/* 底部提示 */
.footer-tip {
  text-align: center;
  padding: 30rpx;
  padding-bottom: 40rpx;
}

.tip-text {
  font-size: 22rpx;
  color: #999;
}

/* 附件样式 */
.attachment-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx;
  margin-bottom: 20rpx;
  background: #f9fafb;
  border-radius: 12rpx;
  border: 2rpx solid #e5e7eb;
  transition: all 0.3s ease;
  cursor: pointer;
}

.attachment-item:active {
  transform: scale(0.98);
  background: #f0f0f0;
}

.attachment-item:last-child {
  margin-bottom: 0;
}

.attachment-preview {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.preview-text {
  font-size: 28rpx;
  color: #1890ff;
  font-weight: 500;
}
</style>
